package MyBlog.dao.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.opensymphony.xwork2.ActionContext;

import MyBlog.dao.ArticleDao;
import MyBlog.entity.Article;

@Repository("articleDao")
public class ArticleDaoImpl implements ArticleDao {

	@Autowired
	private HibernateTemplate hibernateTemplate;	
	
	public static void main(String[] args) {
		ApplicationContext atx = new ClassPathXmlApplicationContext("beans.xml");
		ArticleDao target = (ArticleDao) atx.getBean("articleDao");
		target.delete(11);
	}

	public List<Article> getListByClicks(final int pageSize) {
		return hibernateTemplate.execute(new HibernateCallback<List<Article>>() {
			public List<Article> doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria cri = session.createCriteria(Article.class);
				cri.add(Restrictions.eq("state", 1));
				cri.addOrder(Order.desc("clicks"));
				return cri.setFirstResult(0).setMaxResults(pageSize).list();
			}
		});
	}

	public List<Article> getListByUpdateTime(final int pageSize) {
		return hibernateTemplate.execute(new HibernateCallback<List<Article>>() {
			public List<Article> doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria cri = session.createCriteria(Article.class);
				cri.add(Restrictions.eq("state", 1));
				cri.addOrder(Order.desc("updateTime"));
				return cri.setFirstResult(0).setMaxResults(pageSize).list();
			}
		});
	}

	public List<Article> getListByUserIdAndCid(final int cid ,final int userId, final int pageNum, final int pageSize) {
		return hibernateTemplate.execute(new HibernateCallback<List<Article>>() {
			public List<Article> doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria cri = session.createCriteria(Article.class);
				cri.createAlias("user", "u").add(Restrictions.eq("u.id", userId));
				if(cid > 0)
					cri.createAlias("category", "c").add(Restrictions.eq("c.id", cid));
				cri.add(Restrictions.eq("state", 1));
				cri.addOrder(Order.desc("updateTime"));
				return cri.setFirstResult((pageNum-1)*pageSize)
						.setMaxResults(pageSize)
						.list();
			}
		});
	}

	public int getRowsByUserId(int userId,int cid) {
		List<Article> list = (List<Article>) hibernateTemplate.find("from Article a where a.user.id = ? and a.state = 1",userId);
		if(cid > 0 )
			list = (List<Article>) hibernateTemplate.find("from Article a where a.user.id = ? and a.state = 1 and a.category.id=?",userId,cid);
		return list.size();
	}

	public List<Article> getClicksListByUserId(final int userId, final int pageSize) {
		return hibernateTemplate.execute(new HibernateCallback<List<Article>>() {
			public List<Article> doInHibernate(Session session)
					throws HibernateException, SQLException {
				return session.createQuery("from Article a where a.user.id = ? and a.state = 1")
						.setInteger(0, userId)
						.setMaxResults(pageSize)
						.list();
			}
		});
	}

	public Article fetchArticleById(int articleId) {
		return hibernateTemplate.get(Article.class, articleId);
	}

	public List<Article> getListByCidAndtitle(final int cid, final String title, final int userId) {
		return hibernateTemplate.execute(new HibernateCallback<List<Article>>() {
			public List<Article> doInHibernate(Session session)
					throws HibernateException, SQLException {
				String hql = "from Article a where 1=1 and a.user.id = :userId";
				Map<String,Object> list = new HashMap<String, Object>();
				list.put("userId", userId);
				if(cid>0){
					hql += " and a.category.id = :cid";
					list.put("cid", cid);
				}
				if(title != null && !title.isEmpty()){
					hql+=" and a.title like :title";
					list.put("title", "%"+title+"%");
				}
				return session.createQuery(hql).setProperties(list).list();
			}
		});
	}

	public void update(Article article) {
		hibernateTemplate.update(article);
	}

	@Override
	public void add(Article article) {
		hibernateTemplate.save(article);
	}

	@Override
	public void delete(int articleId) {
		hibernateTemplate.delete(hibernateTemplate.get(Article.class, articleId));
	}
	
}
